package net.zjitc.android2019.ch3storage;

import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import net.zjitc.android2019.R;

public class Ch3SPActivity extends AppCompatActivity {
    Button btn_read,btn_write;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ch3_sp);
        btn_read=findViewById(R.id.ch3_file_sp_btn_read);
        btn_write=findViewById(R.id.ch3_file_sp_btn_write);
        textView=findViewById(R.id.ch3_file_sp_tv);

        View.OnClickListener listener=new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.ch3_file_sp_btn_write:
                        write();
                        break;
                    case R.id.ch3_file_sp_btn_read:
                        read();
                        break;
                }
            }
        };

        btn_read.setOnClickListener(listener);
        btn_write.setOnClickListener(listener);
    }

    /**
     * 从SharedPreferences 读取内容展示在TextView
     */
    private void read() {
        SharedPreferences sp=this.getSharedPreferences("pyt",MODE_PRIVATE);
        String name=sp.getString("name",null);
        int age=sp.getInt("age",0);
        textView.setText(name+" "+age);
    }

    /**
     * 把内容写入到SharedPreferences
     * 该文件时xml格式，key-value结构
     */
    private void write() {
        SharedPreferences sp=this.getSharedPreferences("pyt",MODE_PRIVATE);
        SharedPreferences.Editor editor=sp.edit();
        editor.putString("name","zhangsan");
        editor.putInt("age",20);
        editor.commit();
        Toast.makeText(this, "写入成功", Toast.LENGTH_SHORT).show();
    }
}
